package com.sentinel.demo.basic.controller;


import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import com.sentinel.demo.basic.common.InitRuleUtils;
import com.sentinel.demo.common.SpringBeanUtils;
import com.sentinel.demo.common.Swagger2Config;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
        import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Currency;
import java.util.List;

/**
 * https://www.jianshu.com/p/f354e5b351f0
 * @author dsy on 2019/12/7
 */

@Slf4j
@RestController
public class BasicController {
    public static final String KEY = "listBrand";

    @SentinelResource(value = KEY,blockHandler = "blockHandle" ,fallback = "fallBack")
    @ApiOperation(value = "基本测试1")
    @RequestMapping(value = "/listBrand", method = RequestMethod.GET)
    public String listBrand(String id){
        log.info("listBrand id = {}，当前时间:{}",id , LocalDateTime.now().toLocalTime().toString());
        doSometing();
        return "listBrand OK";
    }

    @SentinelResource(value = "listBrand2",blockHandler = "blockHandle" ,fallback = "fallBack")
    @ApiOperation(value = "基本测试2")
    @RequestMapping(value = "/listBrand2", method = RequestMethod.GET)
    public String listBrand2(String id){
        log.info("listBrand2 id = {}，当前时间:{}",id , LocalDateTime.now().toLocalTime().toString());
        return "listBrand2 OK";
    }
    //发生blocked时，如果blockHandler 和fallback同时写，则blockHandler 优先生效。
    @SentinelResource(value = "listBrand3",blockHandler = "blockHandle")
    @ApiOperation(value = "基本测试3")
    @RequestMapping(value = "/listBrand3", method = RequestMethod.GET)
    public String listBrand3(String id){
        doSometing();
        log.info("listBrand3 id = {}",id);
        log.info("当前时间:{}", LocalDateTime.now().toLocalTime().toString());
        return "listBrand3 OK";
    }

    /**
     * 立马抛异常
     */
    public void doSometing(){
        throw new RuntimeException("do sth. exception...");
    }

    public static String blockHandle(String id ,BlockException be){
        String str = "访问过于频繁，请稍后重试" + LocalDateTime.now().toLocalTime().toString() + "e:" + be.getClass().getSimpleName() + "-" +  be.getMessage();
        System.out.println(str);
        return str;
    }
    public String fallBack(String id){
        String str = "服务异常，请稍后重试：fallBack ,id=" + id + ","+LocalDateTime.now().toLocalTime().toString();
        System.out.println(str);
        return str;
    }
}
